package com.example.hellospringboot.testWebMVC.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class FileController {
//    跳转到upload页面
@GetMapping("/toUpload")
public String toUpload(){
    return "upload";
}
@PostMapping("uploadFile")
//实现文件上传
    public String uploadFile(MultipartFile[] fileUpload, Model model){
//    返回上传成功后的状态信息
        for (MultipartFile file:fileUpload){
//            获取上传文件的名称及后缀名
            String originalFilename=file.getOriginalFilename();
//            重新生成文件名
            String fileName= UUID.randomUUID()+"-"+originalFilename;
//            设置存储目录
            String dirPath="E:\\JavaWeb练习及作业\\HelloSpringBoot\\document\\file";
//            如果文件夹不存在，还要创建
            File file1=new File(dirPath);
            if(!file1.exists()){
                file1.mkdir();
            }
            try {
                file.transferTo(new File(dirPath+fileName));
            }catch (IOException e){
                e.printStackTrace();
                model.addAttribute("uploadStatus","上传失败");
            }

        }
        return "upload";
    }

//    跳转到download页面
@GetMapping("/toDownload")
public String toDownload(){
    return "download";
}
//文件下载
    @GetMapping("/download")
    public ResponseEntity<byte[]> fileDownload(String filename){
//    指定要下载的文件路径
        String dirPath="E:\\JavaWeb练习及作业\\HelloSpringBoot\\file";
//        创建文件对象
        File file=new File(dirPath+File.separator+filename);
//        设置响应头
        HttpHeaders httpHeaders=new HttpHeaders();
//        通知浏览器以下载的形式打开
        httpHeaders.setContentDispositionFormData("attachment",filename);
//        定义以流的形式下载返回文件数据
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        try {
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file),httpHeaders, HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseEntity<byte[]>(e.getMessage().getBytes(),HttpStatus.EXPECTATION_FAILED);
        }
    }
}
